// Learn TypeScript:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/typescript.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/life-cycle-callbacks.html

const { ccclass, property, requireComponent } = cc._decorator;

@ccclass()
@requireComponent(cc.Camera)
export default class SpeedyCamera extends cc.Component {

    @property(cc.RigidBody)
    target: cc.RigidBody = null;

    private _camera: cc.Camera = null

    onLoad() {
        this._camera = this.getComponent(cc.Camera)
    }

    start() {
    }

    changeSpeed: number = 1.5
    zoomRatio: number = 1

    minSpeed: number = 800
    maxSpeed: number = 2000
    update(dt: number) {
        if (!this.target) {
            return
        }
        let speed = this.target.linearVelocity.mag()
        if (speed > this.maxSpeed) {
            speed = this.maxSpeed
        }
        if (speed < this.minSpeed) {
            this.zoomRatio = 1
        } else {
            this.zoomRatio = 1 - (speed - this.minSpeed) / (500 + this.maxSpeed)
        }

        if (this._camera.zoomRatio < this.zoomRatio) {
            this._camera.zoomRatio += this.zoomRatio * dt
            if (this._camera.zoomRatio > this.zoomRatio) {
                this._camera.zoomRatio = this.zoomRatio
            }
        } else if (this._camera.zoomRatio > this.zoomRatio) {
            this._camera.zoomRatio -= this.zoomRatio * dt
            if (this._camera.zoomRatio < this.zoomRatio) {
                this._camera.zoomRatio = this.zoomRatio
            }
        }
    }
}
